$(function() {

    var form = $('#task');

    //门店自动补全
    $('#store_address').autocomplete({
        lookup: (function() {
            var s = [];
            STORE_LIST.forEach(function(item) {
                s.push({value: ' ' + item.title, data: item.id});
            });
            return s;
        })(),
        onSelect: function (suggestion) {
            $('#store_address').val($.trim(suggestion.value));
            form.find('[name="store_id"]').val(suggestion.data);
        }
    });

    //海报上传
    $('#upload').on('click', function() {
        var data = {};
        form.serializeArray().forEach(function (item) {
            data[item['name']] = item['value'];
        });
        data.image = form.find('[name="image"]').val();

        if (!data.store_id || !data.store_name) {
            form.find('.js-store').addClass('error');
            $('.error-info').html('请选择门店').show();
            return false;
        }

        if (!data.image || !data.image_data) {
            form.find('.js-image').addClass('error');
            $('.error-info').html('请上传图片').show();
            return false;
        }

        form.submit();
    });

    //文本框获取焦点清空错误提示
    $('#task input').focus(function() {
        $(this).parent('.field').removeClass('error');
    });

    //重新选择图片
    form.find('[name="image"]').on('change', function() {
        var image = $(this).get(0).files[0];
        var reader = new FileReader();
        reader.onloadend = function () {
            form.find('[name="image_data"]').val(reader.result.split(',')[1]);
        }
        if (image) {
            reader.readAsDataURL(image);
        } else {
            form.find('[name="image_data"]').val('');
        }
    });
});